//
//  EFShareCommentButton.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/3/9.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "EFShareCommentButton.h"
#import "EFengContent.h"

@implementation EFShareCommentButton

- (void)setHighlighted:(BOOL)highlighted
{
    
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(didLongPress:)];
        longPress.minimumPressDuration = 0.4f;
        [self addGestureRecognizer:longPress];

    }
    return self;
}


- (void)didLongPress:(UILongPressGestureRecognizer *)longPress
{
    if(longPress.state != UIGestureRecognizerStateBegan || ![self becomeFirstResponder])
        return;
    UIMenuController *menu = [UIMenuController sharedMenuController];
    
    
    
    CGRect targetRect = [self convertRect:self.frame
                                 fromView:self];
    [menu setTargetRect:CGRectInset(targetRect, 0.0f, 4.0f) inView:self];
    [menu setMenuVisible:YES animated:YES];
    //    [self handleLongText];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleMenuWillShowNotification:)
                                                 name:UIMenuControllerWillShowMenuNotification
                                               object:nil];
    
}

#pragma mark - Copying
- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (BOOL)becomeFirstResponder
{
    return [super becomeFirstResponder];
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    [super canPerformAction:action withSender:sender];
    if(action == @selector(copy:))
        return YES;
    //    if (action==@selector(delete:)) {
    //        return YES;
    //    }
    return NO;
}


- (void)copy:(id)sender
{
    [[UIPasteboard generalPasteboard] setString:self.comment.content];
    [self resignFirstResponder];
}



#pragma mark - Notification
- (void)handleMenuWillHideNotification:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIMenuControllerWillHideMenuNotification
                                                  object:nil];
}

- (void)handleMenuWillShowNotification:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIMenuControllerWillShowMenuNotification
                                                  object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleMenuWillHideNotification:)
                                                 name:UIMenuControllerWillHideMenuNotification
                                               object:nil];
    
}

@end
